package com.sxbbc.common.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.encrypts.des.DESEncode;
import com.sxbbc.common.basics.utils.encrypts.pwd.Encode;
import com.sxbbc.common.basics.utils.regular.RpxUtils;
import com.sxbbc.common.basics.utils.statics.DynamicSettingUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.AgentLevelEnums;
import com.sxbbc.common.core.enums.CashTypeEnums;
import com.sxbbc.common.core.enums.UserFreezeEnums;
import com.sxbbc.common.core.mapper.jz.AgAgentMapper;
import com.sxbbc.common.core.mapper.jz.BankDetailMapper;
import com.sxbbc.common.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.core.utils.BasePage;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 代理用户信息表 服务实现类
 * </p>
 *
 * @author leehao
 * @since 2019-07-08
 */
@Service
public class AgAgentServiceImpl extends ServiceImpl<AgAgentMapper, AgAgent> implements IAgAgentService {

    @Autowired
    private IAgAccountService agAccountService;
    @Autowired
    private ICCustomerService icCustomerService;
    @Autowired
    private ISysCashDetailsService iSysCashDetailsService;
    @Autowired
    private BankDetailMapper bankDetailMapper;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICCustomerAuthenService customerAuthenService;
    @Autowired
    private IAgAgentService iAgAgentService;
    @Autowired
    private IAgMoneyDetailService agMoneyDetailService;
    @Autowired
    private HttpServletRequest request;

    @Override
    public IPage<AgAgent> queryAgentList(BasePage<AgAgent> page, AgAgent agent) {
        baseMapper.queryAgentProfit(page, agent);
        for (AgAgent ag : page.getRecords()) {
            ag.setLevelName(AgentLevelEnums.getName(ag.getLevel()));
            ag.setPassWord(null);
            ag.setPayWord(null);
            BigDecimal sumCash = agMoneyDetailService.querySumCash(ag.getId());
            ag.setSumCash(sumCash);
        }
        return page;
    }

    @Override
    public AgAgent selectByLogin(String login) {
        QueryWrapper<AgAgent> wrapper = new QueryWrapper<>();
        wrapper.eq("login", login);
        return super.getOne(wrapper);
    }

    @Override
    public AgAgent getAreaAgent(Integer addressId, Integer level) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        QueryWrapper<AgAgent> queryWrapper = new QueryWrapper<>();
        if (calcuUtils.isEquals(level, AgentLevelEnums.PROVINCE_AGENT.getId())) {
            queryWrapper.eq("pro_id", addressId);
        } else if (calcuUtils.isEquals(level, AgentLevelEnums.CITY_AGENT.getId())) {
            queryWrapper.eq("city_id", addressId);
        } else if (calcuUtils.isEquals(level, AgentLevelEnums.AREA_AGENT.getId())) {
            queryWrapper.eq("area_id", addressId);
        } else {
            return null;
        }
        queryWrapper.eq("level", level).eq("status",StaticUtils.STATUS_SUCCESS);
        return super.getOne(queryWrapper);
    }

    @Override
    public RestResponse editAgent(AgAgent agent) {
        CalcuUtils calUtil = CalcuUtils.getInstance();
        if (StringUtils.isBlank(agent.getLogin())) {
            return GetRest.getFail("请输入登录名");
        }
        Integer cid = null;
        if (agent.getId() == null) {
            //登录名重复检测
            AgAgent existAgent = this.selectByLogin(agent.getLogin());
            if (existAgent != null) {
                return GetRest.getFail("该登录名已存在！");
            }

            //绑定用户
            if (StringUtils.isBlank(agent.getPhone())) {
                return GetRest.getFail("请输入用户手机号码");
            }
            RpxUtils rpxUtil = RpxUtils.getInstance();
            if (!StringUtils.equals(rpxUtil.validPhone(agent.getPhone()), "")) {
                return GetRest.getFail(rpxUtil.validPhone(agent.getPhone()));
            }
            CCustomer customer = new CCustomer();
            customer.setPhone(agent.getPhone());
            CCustomer cCustomer = icCustomerService.getCustomer(customer);
            if (cCustomer == null) {
                return GetRest.getFail("该用户不存在");
            }
            //XXX 代理账户和用户一对一
            QueryWrapper<AgAgent> queryWrapper = new QueryWrapper<AgAgent>();
            queryWrapper.eq("cid", cCustomer.getId());
            List<AgAgent> oldAgent = super.list(queryWrapper);
            if (!CollectionUtils.isEmpty(oldAgent)) {
                return GetRest.getFail("该用户已经绑定代理");
            }
            agent.setCid(cCustomer.getId());
            cid = cCustomer.getId();
        }

        if (StringUtils.isBlank(agent.getName())) {
            return GetRest.getFail("请输入代理用户名字");
        }
        if (agent.getProId() == null) {
            return GetRest.getFail("请选择省份");
        }
        if (agent.getCityId() == null) {
            return GetRest.getFail("请选择城市");
        }
        if (agent.getLevel() == null) {
            return GetRest.getFail("请选择代理等级");
        }
        //同级别 同地区是否允许重复
        if (DynamicSettingUtils.ALLOW_AGENT_DUPLICATE) {
            QueryWrapper<AgAgent> wrapper = new QueryWrapper<>();
            if (calUtil.isEquals(agent.getLevel(), AgentLevelEnums.PROVINCE_AGENT.getId())) {
                wrapper.eq("level", AgentLevelEnums.PROVINCE_AGENT.getId()).
                        eq("pro_id", agent.getProId());
            } else if (calUtil.isEquals(agent.getLevel(), AgentLevelEnums.CITY_AGENT.getId())) {
                wrapper.eq("level", AgentLevelEnums.CITY_AGENT.getId()).
                        eq("city_id", agent.getCityId());
            } else if (calUtil.isEquals(agent.getLevel(), AgentLevelEnums.AREA_AGENT.getId())) {
                wrapper.eq("level", AgentLevelEnums.AREA_AGENT.getId()).
                        eq("area_id", agent.getAreaId());
            }
            if (agent.getId() != null) {
                wrapper.ne("id", agent.getId());
            }
            int exist = super.count(wrapper);
            if (exist > 0) {
                return GetRest.getFail("该级别与地区已存在代理，不可重复添加！");
            }
        }
        if (agent.getId() == null) {
            agent.setStatus(StaticUtils.STATUS_SUCCESS);
            //登录密码
            agent.setPassWord(DESEncode.getInstance().encrypt(StaticUtils.DEFAULT_PASSWORD));
            //交易密码
            agent.setPayWord(Encode.md5Encode(StaticUtils.DEFAULT_PASSWORD));
        }
        String addressExt = addressService.getAddrName(agent.getProId(), agent.getCityId(), agent.getAreaId());
        agent.setAddressExt(addressExt);
        agent.setRoleId(1);
        boolean save = super.saveOrUpdate(agent);
        if (!save) {
            throw new ThrowJsonException("保存代理用户失败");
        }
        //账户
        AgAccount account = agAccountService.selectByAgid(agent.getId());
        if (account == null) {
            if (cid == null) {
                throw new ThrowJsonException("保存代理用户失败");
            }
            account = new AgAccount(agent.getId(), cid);
            save = agAccountService.save(account);
            if (!save) {
                throw new ThrowJsonException("建立代理账户失败");
            }
        }
        return GetRest.getSuccess("保存成功");
    }

    @Override
    public RestResponse cashApply(SysCashDetails cashDetails, String payWord) {
        CCustomer customer = icCustomerService.getById(cashDetails.getTargetId());

        if (CalcuUtils.getInstance().isEquals(customer.getStatus(), StaticUtils.STATUS_NO)) {
            icCustomerService.checkFrezeeCustomer(UserFreezeEnums.CUSTOMER_CASH.getId(), null);
        }

        if (!CalcuUtils.getInstance().isEquals(customer.getAuthen(), StaticUtils.STATUS_YES)) {
            return GetRest.getFail("请先进行身份认证", null, "2");
        } else {
            //实名认证后需要判断该用户是否绑定银行卡
            QueryWrapper<CCustomerAuthen> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cid", cashDetails.getTargetId());
            CCustomerAuthen authen = customerAuthenService.getOne(queryWrapper);
            if (authen == null) {
                return GetRest.getFail("请求错误，错误代码0000");
            } else if (StringUtils.isBlank(authen.getBankCard())) {
                //验证银行卡是否绑定
                int count = bankDetailMapper.countBankDetailByTargetId(cashDetails.getTargetId());
                if (count == 0) {
                    return GetRest.getFail("请先绑定银行卡");
                }
            }
        }

        // 校验密码
        if (StringUtils.isEmpty(payWord)) {
            return GetRest.getFail("请输入支付密码");
        }
        String encryPayword = Encode.md5Encode(payWord);
        if (!encryPayword.equals(customer.getPayWord())) {
            if (StringUtils.isBlank(customer.getPayWord())) {
                return GetRest.getFail("您还未设置支付密码", null, "1");
            } else {
                return GetRest.getFail("支付密码不正确");
            }
        }
        AgAgent agent = iAgAgentService.getOne(new QueryWrapper<AgAgent>().eq("cid", customer.getId()));
        cashDetails.setTargetId(agent.getId());
        cashDetails.setType(CashTypeEnums.AGENT.getId());
        return iSysCashDetailsService.handleCashApply(cashDetails);
    }
}
